<?php


namespace App\common\tools;



use GuzzleHttp\Client;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Db;

class AliyunOssTools
{
    const ENDPOINT = 'https://yangzhu360-oss.oss-cn-beijing.aliyuncs.com';

    private $accessKeyId = "LTAIP5sEqnIQS0Kj";
    private $accessKeySecret = "DeSs44CeVPR74WfDhRKCYYESJfVuzx";
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private $endpoint = "https://oss-cn-beijing.aliyuncs.com";
    // 设置存储空间名称
    private $bucket = "yangzhu360-oss";
    private $ossClient = null;


    /**
     * AliyunOssTools constructor.
     * @param array $config
     * @author 刘宏盟
     */
    public function __construct($config = [])
    {
        $this->accessKeySecret = $config['accessKeySecret'] ?? $this->accessKeySecret;
        $this->accessKeyId = $config['accessKeyId'] ?? $this->accessKeyId;
        $this->endpoint = $config['endpoint'] ?? $this->endpoint;
        $this->bucket = $config['bucket'] ?? $this->bucket;
    }


    /**
     * 阿里云上传oss文件
     * @param $filePath string 本地文件真实路径
     * @param $folder string 远程文件路径
     * @throws
     * @author 刘宏盟
     */
    public function uploadImage($filePath, $folder)
    {
        try {
            $this->getClient()->uploadFile($this->bucket, $folder, $filePath);
        } catch (OssException $e) {
            app()->log->error($e->getMessage());
        }
    }

    /**
     * 通过url上传图片
     * @param $url
     * @param $ossPath
     * @return string
     * @throws ApiException
     * @author 刘宏盟
     */
    // public function uploadUrl($url, $ossPath)
    // {
    //     $tempHandle = tmpfile();
    //     $tempFile = stream_get_meta_data($tempHandle)["uri"];
    //     // 复制图片到临时文件
    //     $ch = curl_init($url);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     file_put_contents($tempFile, curl_exec($ch));
    //     curl_close($ch);
    //
    //     //上传缩略图
    //     $this->uploadImage($tempFile, $ossPath);
    //
    //     // 删除关闭文件
    //     fclose($tempHandle);
    //     return $this->getBucketDomain() . $ossPath;
    // }

    /**
     * @return OssClient
     * @throws ApiException
     * @author 刘宏盟
     */
    private function getClient(): OssClient
    {
        if ($this->ossClient) {
            return $this->ossClient;
        }
        try {
            $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint);
        } catch (OssException $e) {

        }
        return $this->ossClient;
    }

    /**
     * @param $config
     * @return object|AliyunOssTools
     * @author 刘宏盟
     */
    public static function instance($config = [])
    {
        return app(AliyunOssTools::class, ['config' => $config]);
    }

    /**
     * @param string $ossFilePath
     * @return mixed|string
     * @author 刘宏盟
     */
    public function getBucketDomain($ossFilePath = '')
    {
        return "https://cdn.yangzhu360.com/" . $ossFilePath;
    }

    /**
     * 不是用后缀
     * @param $url
     * @param $vOssPath
     * @return mixed|string|string[]
     * @throws ApiException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function uploadUrl($url, $vOssPath, $noYz360 = true)
    {
        $uri = parse_url($url);
        if ($uri['host'] == 'nimg.ws.126.net') {
            $url = str_replace('&amp;', '&', $url);
        }
        if (strEndsWith($uri['host'], 'yangzhu360.com') && $noYz360) {
            return $url;
        }

        //var_dump($url);die;
        $tempHandle = tmpfile();
        $tempFile = stream_get_meta_data($tempHandle)["uri"];

        $response = (new Client())->request('GET', $url, [
            'verify' => false,
            'headers' => [
                "Connection" => "Keep-Alive",
                "Accept" => "text/html,application/xhtml+xml, */*",
                "Pragma" => "no-cache",
                "Accept-Language" => "zh-Hans-CN,zh-Hans;q=0.8,en-US;q=0.5,en;q=0.3",
                "User-Agent" => "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)",
            ]
        ]);
        file_put_contents($tempFile, $response->getBody());

        $suffix = getFileSuffix($tempFile);
        $vOssPath = $vOssPath . '.' . $suffix;
        //上传缩略图
        $this->uploadImage($tempFile, $vOssPath);
        // 删除关闭文件
        fclose($tempHandle);
        // dump($suffix);
        if($suffix == 'webp') {
            // $suffix .= '?x-oss-process=image/format,png';
            $url = $this->getBucketDomain($vOssPath);
            $vOssPath = date('Y/md/') . sha1($url);
            return $this->uploadUrl($url.'?x-oss-process=image/format,png', $vOssPath, false);
        }

        Db::table('ea_system_uploadfile')->insert([
            'upload_type'=>'alioss',
            'url'=>'https://cdn.yangzhu360.com/'.$vOssPath,
            'original_name' => 'oss',
            'mime_type'=>'image/'.$suffix,
            'file_ext'=>$suffix,
            'create_time'=>time()
        ]);

/*        Attachment::query()->insert([
            'module' => 'content' ,
            'catid' => '0',
            'filename' => 'oss',
            'filepath' => $vOssPath,
            'filesize' => 0,
            'fileext' => 'oss',
            'isimage' => 1,
            'isthumb' => 0,
            'downloads' => 0,
            'userid' => 1,
            'uploadtime' => time(),
            'uploadip' => request()->ip(),
            'status' => 1,
            'authcode' => uniqid(),
            'siteid' =>1
        ]);*/
        return $this->getBucketDomain($vOssPath);
    }

    /**
     * 已经代码了后缀
     * @param $content
     * @param $ossPath
     * @param string $head
     * @return mixed|string
     * @throws ApiException
     */
    public function base64ImageUpload($content, $ossPath, $head = '')
    {
        if (!$head) {
            preg_match('/^(data:\s*image\/(\w+);base64,)/', $content, $result);
            $head = $result[1];
        }
        $tempHandle = tmpfile();
        $tempFile = stream_get_meta_data($tempHandle)["uri"];
        file_put_contents($tempFile, base64_decode(str_replace($head, '', $content)));

        $this->uploadImage($tempFile, $ossPath);
        // 删除关闭文件
        fclose($tempHandle);
        Db::table('ea_system_uploadfile')->insert([
            'upload_type'=>'alioss',
            'url'=>'https://cdn.yangzhu360.com/'.$vOssPath,
            'original_name' => 'oss',
            'mime_type'=>'image/'.$suffix,
            'file_ext'=>$suffix,
            'create_time'=>time()
        ]);

        return $this->getBucketDomain($ossPath);

    }

    private function getFileSuffix($tempFile)
    {

    }

}
